package com.wetao.module_pen.fragment;

import android.content.Context;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.wetao.lib_common.Constants;
import com.wetao.lib_common.base.BaseNestingLazyFragment;
import com.wetao.lib_common.contract.EmptyCon;
import com.wetao.lib_common.greendao.DBUtils;
import com.wetao.lib_common.greendao.model.AssistantExam;
import com.wetao.lib_common.greendao.model.PagePicture;
import com.wetao.lib_common.greendao.model.PenOffLineGridInfo;
import com.wetao.lib_common.presenter.EmptyPre;
import com.wetao.lib_common.utils.DialogXUtil;
import com.wetao.lib_common.utils.FileUtils;
import com.wetao.lib_common.utils.LogUtils;
import com.wetao.lib_common.utils.SPUtils;
import com.wetao.lib_common.utils.StringUtil;
import com.wetao.lib_common.view.decoration.SpacesItemDecoration;
import com.wetao.lib_common.view.pagerphoto.ShowImagesDialog;
import com.wetao.module_pen.R;
import com.wetao.module_pen.R2;
import com.wetao.module_pen.adapter.PenSubmitFragmentAdapter;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

public class PenSubmitFragment extends BaseNestingLazyFragment<EmptyCon.View, EmptyPre> implements EmptyCon.View  {

    private static final String ARG_PARAM1 = "param1";
    private String mParam1;

    @BindView(R2.id.ll_bottom)
    LinearLayout ll_bottom;
    @BindView(R2.id.iv_all_select)
    ImageView iv_all_select;
    @BindView(R2.id.tv_select_num)
    TextView tv_select_num;
    @BindView(R2.id.iv_no_data)
    ImageView iv_no_data;
    @BindView(R2.id.tv_no_data)
    TextView tv_no_data;

    @BindView(R2.id.recycler_view)
    RecyclerView mRecyclerView;
    private GridLayoutManager mGridLayoutManager;
    private PenSubmitFragmentAdapter mPenSubmitAdapter;

    private final List<String> mPhotoList = new ArrayList<>();
    private ShowImagesDialog mImagesDialog;

    private Disposable mDisposable;



    private OnFragmentInteractionListener mListener;

    public PenSubmitFragment() {
    }

    public static PenSubmitFragment newInstance(/*String param1*/) {
        PenSubmitFragment fragment = new PenSubmitFragment();
        Bundle args = new Bundle();
        //args.putString(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.pen_submit_fragment;
    }

    @Override
    public EmptyPre createPresenter() {
        return new EmptyPre(mContext);
    }

    @Override
    public EmptyCon.View createView() {
        return this;
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }

    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        rxjava_disposable();
        super.onDestroyView();
        /*if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }*/
    }

    private void rxjava_disposable() {
        if(mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
            mDisposable = null;
        }
    }

    @Override
    public void onFragmentFirst() {
        super.onFragmentFirst();
        /*if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }*/
        //reLoadData();
    }

    @Override
    public void onFragmentVisble() {
        super.onFragmentVisble();
    }

    @Override
    public void onFragmentInVisible() {
        super.onFragmentInVisible();
    }

    @Override
    public void init(View rootView) {
        if (getArguments() != null) {
            //mParam1 = getArguments().getString(ARG_PARAM1);
        }

        initRecyclerView();


        Observable.timer(500, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer< Long >() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(Long aLong) {
                        LogUtils.d("m1:onNext " + aLong + ", threadName = " + Thread.currentThread().getName());
                        reLoadData();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    @OnClick({R2.id.ll_all_select,
            R2.id.btn_submit
    })
    public void onViewClick(View v) {
        int id = v.getId();
        if(id == R.id.ll_all_select) {
            mPenSubmitAdapter.setAllSelect(!mPenSubmitAdapter.isAllSelect());
            refreshSelectView();

        } else if(id == R.id.btn_submit) {
            if(mPenSubmitAdapter.getmCurSelect() <= 0) {
                DialogXUtil.customDialogShow("请先选择要提交的作答！", "", "好的", true, new DialogXUtil.OnDialogXListen() {
                    @Override
                    public void onListenDialogOk() {

                    }

                    @Override
                    public void onListenDialogCancel() {

                    }

                    @Override
                    public void onListenDialogClose() {

                    }
                });
            } else {
                mPenSubmitAdapter.setSubmit();
            }
        }
    }

    private void refreshSelectView() {
        if(mPenSubmitAdapter.isAllSelect()) {
            iv_all_select.setImageResource(R.drawable.common_select_d);
        } else {
            iv_all_select.setImageResource(R.drawable.common_select_n);
        }
        tv_select_num.setText(mPenSubmitAdapter.getmCurSelect() + "");
        if(mPenSubmitAdapter.getmCount() == 0) {
            ll_bottom.setVisibility(View.GONE);
            iv_no_data.setVisibility(View.VISIBLE);
            tv_no_data.setVisibility(View.VISIBLE);
            mRecyclerView.setVisibility(View.GONE);
        } else {
            ll_bottom.setVisibility(View.VISIBLE);
            iv_no_data.setVisibility(View.GONE);
            tv_no_data.setVisibility(View.GONE);
            mRecyclerView.setVisibility(View.VISIBLE);
        }

        String studentId = SPUtils.getInstance().getString(Constants.USER_ID_KEY);
        SPUtils.getInstance().put(Constants.USER_PEN_OFFLINE_NOSUBMITNUM + "_" + studentId, mPenSubmitAdapter.getmCount());
        if(mListener != null) {
            mListener.on_st_setNoSubmitNum(mPenSubmitAdapter.getmCount());
        }
    }

    private void initRecyclerView() {
        mGridLayoutManager = new GridLayoutManager(mContext, 6);
        mPenSubmitAdapter = new PenSubmitFragmentAdapter(this.getActivity());
        //mRecyclerView.addItemDecoration(new SpacesItemDecoration(0, 1, Color.parseColor("#DDDDDD")));
        mRecyclerView.setLayoutManager(mGridLayoutManager);
        mRecyclerView.setItemAnimator( new DefaultItemAnimator());
        mRecyclerView.setAdapter(mPenSubmitAdapter);

        mGridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override public int getSpanSize(int position) {
                //计算在哪个position时要显示1列数据，即columnCount / 1列 = 4格，即1列数据占满4格
                PenOffLineGridInfo data = mPenSubmitAdapter.getPositionData(position);
                if(data != null) {
                    if (data.showType.intValue() == 2) {
                        return 1;
                    } else {
                        return 6;
                    }
                } else {
                    return 0;
                }
            }

        });

        mPenSubmitAdapter.setOnItemClickListener(new PenSubmitFragmentAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {

            }

            @Override
            public void onRefrshSelect() {
                refreshSelectView();
            }

            @Override
            public void onClickPhotoView(int index) {
                LogUtils.i("onClickPhotoView index = " + index);
                mImagesDialog.setPhotoViewIndex(index);
                mImagesDialog.show();
            }
        });
    }

    private void addUrlPhotoList(PenOffLineGridInfo item) {
        String picFilePath_c = FileUtils.getPicFilePath(mContext, "offline" + File.separator + "c", "" + item.getPicId(), "");
        File file_c = new File(picFilePath_c);
        if(file_c.exists()) {

        } else {
            picFilePath_c = item.getPictureUrl();
            //iv_c_img.setImageResource();
        }
        if(StringUtil.isEmpty(picFilePath_c)) {
            return;
        }
        mPhotoList.add(picFilePath_c);
    }


    //======================================================================
    public void reLoadData() {
        List<PenOffLineGridInfo> gridInfoList =  DBUtils.getInstance(this.getActivity()).getPenOffLineGridInfoAll();
        PenOffLineGridInfo temp = null;
        PenOffLineGridInfo temp_showType1 = null;
        int num = 0;
        int count = 0;
        if(gridInfoList == null) {
            LogUtils.e("没有待提交的数据");
            ll_bottom.setVisibility(View.GONE);
            iv_no_data.setVisibility(View.VISIBLE);
            tv_no_data.setVisibility(View.VISIBLE);
            mRecyclerView.setVisibility(View.GONE);

            String studentId = SPUtils.getInstance().getString(Constants.USER_ID_KEY);
            SPUtils.getInstance().put(Constants.USER_PEN_OFFLINE_NOSUBMITNUM + "_" + studentId, count);
            return;
        }
        List<PenOffLineGridInfo> datas = new ArrayList<>();
        AssistantExam assistantExam = null;//离线在线同步用
        datas.clear();
        mPhotoList.clear();
        for(int i = 0; i < gridInfoList.size(); i++) {
            PenOffLineGridInfo item = gridInfoList.get(i);
            if(temp != null) {
                if(item.getExamId().intValue() != temp.getExamId().intValue()) {

                    if(temp_showType1 != null && temp_showType1.getIsMore() && !temp_showType1.getIsWrite()){

                    } else {
                        PenOffLineGridInfo item3 = item.copy(temp);
                        item3.showType = 3;
                        item3.pageNum = num;
                        item3.isSelect = false;
                        datas.add(item3);
                    }


                    //离线在线同步用 在showType=1后面加
                    assistantExam = DBUtils.getInstance(getActivity()).getAssistantExamByExamId(item.getExamId().intValue());

                    temp_showType1 = item;


                    if(temp_showType1 != null && temp_showType1.getIsMore() && !temp_showType1.getIsWrite()) {
                        //多页但是没有写的，这个函数后面会删除掉，所以计数不加一
                        //DBUtils.getInstance(mContext).deletePenOffLineGridInfoByExamid(item.getExamId());
                    } else {
                        item.showType = 1;
                        item.isSelect = false;
                        if(assistantExam != null && item.getIsMore()) {
                            item.setIsWrite(true);
                        }
                        datas.add(item);
                        count++;
                    }

                    if(temp_showType1 != null && temp_showType1.getIsMore() && !temp_showType1.getIsWrite()){

                    } else {
                        if(assistantExam == null) {
                            PenOffLineGridInfo item2 = item.copy(item);
                            item2.showType = 2;
                            item2.isSelect = false;
                            datas.add(item2);
                            addUrlPhotoList(item2);
                            num = 1;
                        } else {
                            num = addAssistantPicToList(assistantExam, datas);
                        }
                    }

                } else {
                    if(temp_showType1 != null && temp_showType1.getIsMore() && !temp_showType1.getIsWrite()){

                    } else {
                        if (assistantExam == null) {
                            item.showType = 2;
                            item.isSelect = false;
                            datas.add(item);
                            addUrlPhotoList(item);
                            num++;
                        }
                    }
                }
            } else {
                //离线在线同步用 在showType=1后面加
                if (item.getExamId()==null)continue;
                assistantExam = DBUtils.getInstance(getActivity()).getAssistantExamByExamId(item.getExamId().intValue());

                temp_showType1 = item;

                if(temp_showType1 != null && temp_showType1.getIsMore() && !temp_showType1.getIsWrite()) {
                    //多页但是没有写的，这个函数后面会删除掉，所以计数不加一
                    //DBUtils.getInstance(mContext).deletePenOffLineGridInfoByExamid(item.getExamId());
                } else {
                    item.showType = 1;
                    item.isSelect = false;
                    if(assistantExam != null && item.getIsMore()) {
                        item.setIsWrite(true);
                    }
                    datas.add(item);
                    count++;
                }



                if(temp_showType1 != null && temp_showType1.getIsMore() && !temp_showType1.getIsWrite()){

                } else {
                    if (assistantExam == null) {
                        PenOffLineGridInfo item2 = item.copy(item);
                        item2.showType = 2;
                        item2.isSelect = false;
                        datas.add(item2);
                        addUrlPhotoList(item2);
                        num = 1;
                    } else {
                        //离线在线同步用
                        num = addAssistantPicToList(assistantExam, datas);
                    }
                }
            }



            if(i == gridInfoList.size() - 1) {

                if(temp_showType1 != null && temp_showType1.getIsMore() && !temp_showType1.getIsWrite()){

                }else {
                    PenOffLineGridInfo item2 = item.copy(item);
                    item2.showType = 3;
                    item2.pageNum = num;
                    item2.isSelect = false;
                    datas.add(item2);
                }

                PenOffLineGridInfo item3 = item.copy(item);
                item3.showType = 4;
                item3.isSelect = false;
                datas.add(item3);
            }
            temp = gridInfoList.get(i);
        }

        iv_all_select.setImageResource(R.drawable.common_select_n);
        tv_select_num.setText("0");
        mPenSubmitAdapter.setmCount(count);
        mPenSubmitAdapter.setmCurSelect(0);
        mPenSubmitAdapter.updateData(datas);
        if(count == 0) {
            ll_bottom.setVisibility(View.GONE);
            iv_no_data.setVisibility(View.VISIBLE);
            tv_no_data.setVisibility(View.VISIBLE);
            mRecyclerView.setVisibility(View.GONE);
        } else {
            ll_bottom.setVisibility(View.VISIBLE);
            iv_no_data.setVisibility(View.GONE);
            tv_no_data.setVisibility(View.GONE);
            mRecyclerView.setVisibility(View.VISIBLE);
        }
        String studentId = SPUtils.getInstance().getString(Constants.USER_ID_KEY);
        SPUtils.getInstance().put(Constants.USER_PEN_OFFLINE_NOSUBMITNUM + "_" + studentId, count);
        if(mListener != null) {
            mListener.on_st_setNoSubmitNum(count);
        }

        mImagesDialog = new ShowImagesDialog(this.getActivity(), mPhotoList);
    }

    private int addAssistantPicToList(AssistantExam assistantExam, List<PenOffLineGridInfo> datas) {
        if(assistantExam.getPictureList() == null) {
            LogUtils.e("assistantExam.getPictureList() == null");
            return 0;
        }
        int num = 0;
        for(PagePicture item : assistantExam.getPictureList()) {
            String picFilePath_c = null;
            picFilePath_c = FileUtils.getPicFilePath(mContext, "offline" + File.separator + "f", "" + item.getPictureId(), "");

            File file_c = new File(picFilePath_c);
            if(!file_c.exists()) {
                //在线或离线作答有这一页，但是没有作答
                continue;
            }

            num++;
            PenOffLineGridInfo item2 = new PenOffLineGridInfo(null,
                    item.getPictureId(),
                    item.getPageserial(),
                    item.getBookId(),
                    item.getOwnerNo(),
                    item.getSectionNo(),
                    item.getPageNumber(),
                    item.getBigPicWidth(),
                    item.getBigPicHeight(),
                    item.getPictureUrl(),
                    null,
                    null,
                    assistantExam.getExamName(),
                    null,
                    null,
                    null,
                    assistantExam.getExamId(),
                    false,
                    0f,
                    0f,
                    0f,
                    0f,
                    0f,
                    0f,
                    0f,
                    0f,
                    assistantExam.getBeginTime(),
                    null,
                    null,
                    1,
                    false,
                    null,
                    null,
                    null,
                    null
            );;

            item2.showType = 2;
            item2.isSelect = false;
            datas.add(item2);
            addUrlPhotoList(item2);
        }

        return num;
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void on_st_setNoSubmitNum(int count);
    }
}
